package com.xjnt.tvos.tvlibs.jsbridge.data;

import com.xjnt.tvos.tvlibs.jsbridge.annotation.Param;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 *
 * 参数管理器
 *
 * Created by caoyong on 18-1-8.
 */
public class ParamManager {

    private BasicParam[] baseParams;

    private ParamManager() {
    }

    public static ParamManager create(Method method) {
        ParamManager paramManager = null;
        if (null != method) {
            Annotation[][] annotations = method.getParameterAnnotations();
            Class<?>[] paramTypes = method.getParameterTypes();
            if (annotations != null) {
                paramManager = new ParamManager();
                paramManager.baseParams = new BasicParam[annotations.length];
                for (int i = 0; i < annotations.length; i++) {
                    if (annotations[i].length == 0) {
                        throw new IllegalArgumentException("All the arguments in the method must be modified with the annotation \"Param.class\".");
                    }
                    Annotation annotation;
                    for (int j = 0; j < annotations[i].length; j++) {
                        annotation = annotations[i][j];
                        if (null != annotation && annotation instanceof Param) {
                            Param param = (Param) annotation;
                            BasicParam baseParam = null;
                            if (param.type() == Param.ParamType.DATA) {
                                baseParam = new ParamData(param.value(), paramTypes[i]);
                            } else if (param.type() == Param.ParamType.CALLBACK) {
                                baseParam = new ParamCallback(param.value(), paramTypes[i]);
                            } else if (param.type() == Param.ParamType.STATUS) {
                                baseParam = new ParamStatus(param.value(), paramTypes[i]);
                            }
                            paramManager.baseParams[i] = baseParam;
                        }
                    }
                }
            }
        }
        return paramManager;
    }

    public Object[] getValues(DataBuilder dataBuilder) {
        Object[] values = new Object[baseParams.length];
        for (int i = 0; i < baseParams.length; i++) {
            BasicParam param = baseParams[i];
            values[i] = param.getValue(dataBuilder);
        }
        return values;
    }

    public void setValues(DataBuilder dataBuilder, Object[] values) {
        for (int i = 0; i < baseParams.length; i++) {
            BasicParam param = baseParams[i];
            param.setValue(dataBuilder, values[i]);
        }
    }
}
